import { defineStore } from 'pinia'
import type {
  LoginForm,
  LoginResponseData,
  UserResponseData,
} from '@/api/user/type'
import type { RouteRecordRaw } from 'vue-router'
// import type { menuRoutes } from '@/store/type'
import { Login, getUserInfo, reqLogout } from '@/api/user'
import { storage } from '@/utils/storage'
import { reactive, ref } from 'vue'
import {setTimeStamp} from '@/utils/time'

// 引入路由
import { routes, asyncRoutes, anyRoutes } from '@/router/routes'
import router from '@/router'
//引入深拷贝方法
//@ts-ignore
import cloneDeep from 'lodash/cloneDeep'

let userStore = defineStore('user', () => {
  const menuRoutes = ref<RouteRecordRaw[]>(routes) // 菜单数组
  const buttons = ref<string[]>([]) // 按钮权限标识数组
  const token = ref<string | null>(storage.get('token') || null)
  let userInfoData = ref<UserResponseData| any>(null)
  // 登录
  const userLogin = async (data: LoginForm) => {
    let result: LoginResponseData = await Login(data)
    // console.log('result',result)
    if (result.code == 200) {
      token.value = result.data as string
      storage.set('token', result.data as string)
      setTimeStamp()
      return 'ok'
    } else {
      return Promise.reject(new Error(result.data))
    }
  }
  // 获取用户信息
  const userInfo = async () => {
    let data: UserResponseData = await getUserInfo()
    console.log('data',data.data)
    if(data.code == 200) {
      userInfoData.value = data.data
      // 按钮权限
      buttons.value = data.data.buttons
      // 过滤异步路由
      let userAsyncRoutes = filterAsyncRoute(cloneDeep(asyncRoutes), data.data.routes)
      menuRoutes.value = [...routes, ...userAsyncRoutes, ...anyRoutes];
      [...userAsyncRoutes, ...anyRoutes].forEach((route: any) => {
        router.addRoute(route)
      })
      // console.log('data',router.getRoutes())
      return 'ok'
    } else {
      return Promise.reject(new Error(data.message))
    }
  }
  // 退出登录
  const userLogout = async() => {
    let result: any = await reqLogout()
    if(result.code == 200) {
      token.value = null
      userInfoData.value = null
      storage.remove('token')
      storage.remove('hrsaas-timestamp-key')
      return 'ok'
    } else {
      return Promise.reject(new Error(result.message))
    }
    
  }
  return {
    menuRoutes,
    buttons,
    token,
    userInfoData,
    userLogin,
    userInfo,
    userLogout,
  }
})

// 过滤异步路由
const filterAsyncRoute = (asnycRoute: any, routes: any)=> {
  return asnycRoute.filter((item: any) => {
    if (routes.includes(item.name)) {
      if (item.children?.length > 0) {
        item.children = filterAsyncRoute(item.children, routes)
      }
      return true
    }
  })
}
export default userStore
